<?php
namespace app\common\process;

class Server extends Base {
    public function message2() {
        $app = loadTool('Wechat')->OfficialAccount('miniprogram2');
        $app->server->push(function ($message) {
            \think\Log::record('######################');
            \think\Log::record($message);
            \think\Log::record('!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
            $result = '';
            switch ($message['MsgType']) {
                case 'text':
                    // 处理文本消息
                    $result = $this->handleTextMessage($message);
                case 'event':
                    // 处理事件消息（如用户收货事件）
                    $result = $this->handleEventMessage($message);
                default:
                    $result = '收到其他类型消息';
            }
            \think\Log::record('!!!!!!!!!!!!!!!!!!!!!!!!!!!!result');
            \think\Log::record($result);
            return $result;
        });

        $response = $app->server->serve();
        $responseContent = $response->getContent();
        
        // 如果是XML格式，尝试转换为JSON
        if (strpos($responseContent, '<xml>') === 0) {
            $data = $this->xmlToJson($responseContent);
            return loader()->loadAny('response', 'Server')->json($data);
        }
        return loader()->loadAny('response', 'Server')->json($responseContent);
    }

    public function handleTextMessage($message) {
        return "";
    }

    public function handleEventMessage($message) {
        switch ($message['Event']) {
            case 'USER_SHIPPING_ADDRESS':
                return $this->handleShippingAddress($message);
            default:
                return "未知事件: {$message['Event']}";
        }
    }

    public function handleShippingAddress($message) {
        $orderid = $message['OrderId'];
        $order = loadModel('jy\\Order')->find($orderid);
        $orderStatusEnum = loadEnum('OrderStatus');
        if($order->status == $orderStatusEnum->code2key('daishouhuo')) {
            $order->status = $orderStatusEnum->code2key('yiwancheng');
            $order->save();
            return "保存成功";
        } else {
            \think\Log::error('订单不处于待收货状态' . $orderid);
            return "订单不处于待收货状态";
        }
    }

    // XML转JSON辅助方法
    private function xmlToJson($xml)
    {
        $obj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $json = json_encode($obj);
        return json_decode($json, true);
    }


    //发送新订单消息
    public function send_order_pay($order) {

    }
}
